import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/constants/app_constants.dart';

/// 主题Provider
class ThemeProvider extends ChangeNotifier {
  ThemeMode _themeMode = ThemeMode.system;
  late SharedPreferences _prefs;

  ThemeMode get themeMode => _themeMode;

  /// 初始化主题设置
  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
    await _loadTheme();
  }

  /// 加载保存的主题设置
  Future<void> _loadTheme() async {
    final themeIndex = _prefs.getInt(AppConstants.themeKey) ?? 0;
    _themeMode = ThemeMode.values[themeIndex];
    notifyListeners();
  }

  /// 切换主题
  Future<void> setTheme(ThemeMode themeMode) async {
    _themeMode = themeMode;
    await _prefs.setInt(AppConstants.themeKey, themeMode.index);
    notifyListeners();
  }

  /// 切换到明亮主题
  Future<void> setLightTheme() async {
    await setTheme(ThemeMode.light);
  }

  /// 切换到暗黑主题
  Future<void> setDarkTheme() async {
    await setTheme(ThemeMode.dark);
  }

  /// 切换到系统主题
  Future<void> setSystemTheme() async {
    await setTheme(ThemeMode.system);
  }

  /// 获取当前主题名称
  String get themeName {
    switch (_themeMode) {
      case ThemeMode.light:
        return '明亮模式';
      case ThemeMode.dark:
        return '暗黑模式';
      case ThemeMode.system:
        return '跟随系统';
    }
  }

  /// 判断是否为暗黑主题（需要context来检测系统主题）
  bool isDarkModeWithContext(BuildContext context) {
    if (_themeMode == ThemeMode.system) {
      return MediaQuery.of(context).platformBrightness == Brightness.dark;
    }
    return _themeMode == ThemeMode.dark;
  }

  /// 获取当前是否为暗黑模式（不需要context）
  bool get isDarkMode {
    return _themeMode == ThemeMode.dark;
  }

  /// 切换暗黑模式
  Future<void> toggleTheme() async {
    if (_themeMode == ThemeMode.dark) {
      await setTheme(ThemeMode.light);
    } else {
      await setTheme(ThemeMode.dark);
    }
  }
} 